<template>
  <div class="requisition-pool-wrap table-gl-w">
    <a-tabs @change="changeStatus" size="mini">
      <a-tab-pane key="" title="全部" />
      <a-tab-pane v-for="tab in tabs" :key="tab.key" :title="tab.title" />
    </a-tabs>

    <div class="search-w table-filter-form">
      <FilterTable :filterItem="filterItem" :isReset="true" @search="searchByVal" />
    </div>
    <div class="table-gl-con">
      <TableWrap style="flex: 1" @refresh="getTableList">
        <template #headerLeft>
          <a-button v-if="searchVal.paymentStatus === 10 && $authPass('finance.payment.order.audit')" type="primary" size="medium" @click="openAuditDialog(selectIds)">审核</a-button>
          <a-button v-if="searchVal.paymentStatus === 30 && $authPass('finance.payment.order.submit')" type="primary" size="medium" @click="submitAudit(selectIds)">提交审核</a-button>
        </template>
        <template #tableBody>
          <a-table
            class="table-two-line show-border-table"
            ref="tableRef"
            row-key="id"
            :summary="true"
            :loading="tableLoading"
            @sorter-change="sorterChange"
            @selection-change="selectColumn"
            :row-selection="rowSelection"
            :data="tableList"
            :scroll="{
              x: '100%',
              y: '100%',
            }"
            size="mini"
            :pagination="false"
          >
            <template #columns>
              <a-table-column data-index="sort" title="序号" :width="45" fixed="left">
                <template #cell="{ rowIndex }">
                  <p>{{ rowIndex + 1 }}</p>
                </template>
              </a-table-column>
              <a-table-column title="请款单号" :width="110" fixed="left">
                <template #cell="{ record }">
                  <a-space :size="4">
                    <p class="highlight cursor" @click="openBillDetail(record, 'detail')">{{ record.billNo || '--' }}</p>
                    <CopyText :val="record.billNo" class="popup-edit-icon-hover" />
                  </a-space>
                </template>
              </a-table-column>
              <a-table-column title="应付对象" :width="130" fixed="left">
                <template #cell="{ record }">
                  <TextLimit :rows="1" :val="record.supplierName" />
                  <p style="color: #999">{{ record.supplierCode }}</p>
                </template>
              </a-table-column>
              <a-table-column title="关联单据" :width="100" fixed="left">
                <template #cell="{ record }">
                  <p class="highlight">{{ record.relateBillNo || '--' }}</p>
                </template>
              </a-table-column>
              <a-table-column title="付款状态" :width="70">
                <template #cell="{ record }">
                  <p>{{ paymentStatusMap[record.paymentStatus] }}</p>
                  <a-popover :content="record.auditRemark" v-if="record.paymentStatus === 30">
                    <p class="text-limit warningColor">驳回原因：{{ record.auditRemark }}</p>
                  </a-popover>
                </template>
              </a-table-column>
              <a-table-column title="类型" :width="70">
                <template #cell="{ record }">
                  <p>{{ record.settleType === 1 ? '货款现结' : '货款月结' }}</p>
                </template>
              </a-table-column>
              <a-table-column title="紧急程度" :width="70">
                <template #cell="{ record }">
                  <p>{{ urgentStatusMap[record.urgentStatus] }}</p>
                </template>
              </a-table-column>
              <a-table-column title="请款金额" data-index="requestAmount" :width="80">
                <template #cell="{ record }">
                  <p>￥{{ record.requestAmount }}</p>
                </template>
              </a-table-column>
              <a-table-column title="请款人" data-index="requestUname" :width="70" />
              <a-table-column data-index="gmtCreate" title="请款时间" :sortable="sortable" :width="130">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtCreate, 'YYYY-MM-DD HH:mm') }}</p>
                </template>
              </a-table-column>
              <a-table-column title="审核人" data-index="auditUname" :width="70" />
              <a-table-column data-index="gmtAudit" :sortable="sortable" title="审核时间" :width="130">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtAudit, 'YYYY-MM-DD HH:mm') }}</p>
                </template>
              </a-table-column>
              <a-table-column title="付款人" data-index="paymentUname" :width="70" />
              <a-table-column data-index="gmtPayment" title="付款时间" :sortable="sortable" :width="130">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtPayment, 'YYYY-MM-DD HH:mm') }}</p>
                </template>
              </a-table-column>
              <a-table-column data-index="gmtExpectedPayment" title="期望付款日期" :width="130">
                <template #cell="{ record }">
                  <p>{{ $setTime(record.gmtExpectedPayment, 'YYYY-MM-DD') }}</p>
                  <p v-if="record.paymentStatus === 10 || record.paymentStatus === 20 || record.paymentStatus === 30" v-html="getSurplusTime(record.gmtExpectedPayment)"></p>
                </template>
              </a-table-column>

              <a-table-column title="备注" :width="120">
                <template #cell="{ record }">
                  <a-space>
                    <TextLimit :val="record.remark || '--'" />
                    <icon-edit v-if="![0, 40].includes(record.paymentStatus) && $authPass('finance.payment.order.update')" @click="openEditRemarkDialog(record)" class="cursor popup-edit-icon-hover" />
                  </a-space>
                </template>
              </a-table-column>
              <a-table-column title="操作" :width="80" fixed="right">
                <template #cell="{ record }">
                  <a-space>
                    <div>
                      <a-button type="text" v-if="record.paymentStatus === 10 && $authPass('finance.payment.order.audit')" @click="openAuditDialog([record.id])">审核</a-button>
                      <a-button type="text" v-else-if="record.paymentStatus === 20 && $authPass('finance.payment.order.pay')" @click="openBillDetail(record, 'pay')">付款</a-button>
                      <a-button type="text" v-else-if="record.paymentStatus === 30 && $authPass('finance.payment.order.update')" @click="openEditDialog(record)">编辑</a-button>
                      <a-button type="text" v-else @click="openBillDetail(record, 'detail')">详情</a-button>
                    </div>
                    <a-dropdown v-if="![0, 40].includes(record.paymentStatus)">
                      <icon-more class="table-btn-more" />
                      <template #content>
                        <a-doption @click.stop="openEndDialog(record)" v-if="[10, 20].includes(record.paymentStatus) && $authPass('finance.payment.order.cancel')">作废</a-doption>
                        <a-doption @click.stop="submitAudit([record.id])" v-if="[30].includes(record.paymentStatus) && $authPass('finance.payment.order.submit')">提交审核</a-doption>
                        <a-doption @click.stop="openBillDetail(record, 'detail')">详情</a-doption>
                      </template>
                    </a-dropdown>
                  </a-space>
                </template>
              </a-table-column>
            </template>
            <template #summary-cell="{ column }">
              <p v-if="column.dataIndex == 'sort'">合计</p>
              <p v-else-if="['requestAmount'].includes(column.dataIndex)">￥{{ countMap[column.dataIndex] }}</p>
            </template>
          </a-table>
        </template>
      </TableWrap>
      <div class="pagination-footer">
        <a-pagination size="mini" :total="total" :default-page-size="searchVal.pageSize" :current="searchVal.pageNum" :page-size-options="[20, 50, 100, 200, 500]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
      </div>
    </div>
  </div>
  <!-- 审核 -->
  <Audit v-if="showAuditDialog" :isShow="showAuditDialog" @closed="showAuditDialog = false" @success="audit" />
  <!-- 编辑备注 -->
  <a-modal :width="600" v-model:visible="showEditRemarkDialog" :ok-loading="submitLoading" title="备注" title-align="start" :mask-closable="false" @cancel="editRemarkVal = null" :on-before-ok="submitRemark">
    <a-textarea placeholder="输入备注" style="height: 100px" v-model="editRemarkVal" />
  </a-modal>
  <!-- 作废请款单 -->
  <a-modal :width="400" v-model:visible="showEndDialog" :ok-loading="submitLoading" title="请款单作废" title-align="start" :mask-closable="false" :on-before-ok="submitEnd">
    <p style="font-size: 16px">
      确定将请款单
      <span class="highlight" style="margin: 0 5px">{{ currentData.billNo }}</span>
      作废？
    </p>
  </a-modal>
  <!-- 编辑请款单 -->
  <UpdatePayrollRequisition v-if="showUpdateBill" :currentId="currentData.id" :isShow="showUpdateBill" @closed="showUpdateBill = false" @success="getTableList" />
  <!-- 请款单详情 -->
  <PayrollRequisitionDetail :detailType="currentData.detailType" v-if="showBillDetail" :currentId="currentData.id" :isShow="showBillDetail" @closed="showBillDetail = false" @success="getTableList" />
</template>
<script lang="ts" setup>
  import { ref, onMounted, reactive } from 'vue'
  import FilterTable from '@/components/TableFilter.vue'
  import { FilterTableItem } from '@/types/components'
  import TableWrap from '@/components/TableWrap.vue'
  import { Message, Modal } from '@arco-design/web-vue'
  import { findSupperList, findPaymentOrderPage, findPaymentOrderSum, auditPaymentOrder, submitPaymentOrder, updatePaymentOrderRemark, cancelPaymentOrder } from '@/api/purchase'
  import UpdatePayrollRequisition from './components/updatePayrollRequisition.vue'
  import PayrollRequisitionDetail from './components/payrollRequisitionDetail.vue'
  import Audit from '../purchaseManagement/components/audit.vue'
  import dayjs from 'dayjs'

  onMounted(() => {
    getSupplierList()
    getTableList()
  })
  const rowSelection = reactive({
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false,
  }) as any

  const filterItem = ref<Array<FilterTableItem>>([
    {
      key: 'supplierId',
      label: '供应商',
      value: ref(),
      type: 'select',
      width: 140,
      optionItems: [],
    },

    {
      type: 'input_search',
      key: 'billNo',
      value: ref(),
      label: '请款单号',
      width: 140,
    },
    {
      type: 'input_search',
      key: 'relateBillNo',
      value: ref(),
      label: '关联单号',
      width: 140,
    },
    {
      key: 'settleType',
      label: '类型',
      value: ref(),
      type: 'select',
      width: 80,
      optionItems: [
        {
          label: '现结',
          value: 1,
        },
        {
          label: '月结',
          value: 2,
        },
      ],
    },
    {
      key: 'urgentStatus',
      label: '紧急程度',
      value: ref(),
      type: 'select',
      width: 100,
      optionItems: [
        {
          label: '正常',
          value: 0,
        },
        {
          label: '加急',
          value: 1,
        },
        {
          label: '紧急',
          value: 2,
        },
      ],
    },
    {
      type: 'input_keyword',
      key: 'requestUname',
      keyItems: [
        { label: '请款人', value: 'requestUname' },
        { label: '审核人', value: 'auditUname' },
        { label: '付款人', value: 'paymentUname' },
      ],
      keyWidth: 90,
      value: ref(),
      placeholder: '请输入',
      label: '请款人',
      width: 120,
      isMultiple: false,
    },
    {
      type: 'keyword_date_range',
      key: 'gmtCreate',
      keyItems: [
        { label: '请款时间', value: 'gmtCreate' },
        { label: '审核时间', value: 'gmtAudit' },
        { label: '付款时间', value: 'gmtPayment' },
        { label: '期望付款日期', value: 'gmtExpectedPayment' },
      ],
      keyWidth: 130,
      value: ref(),
      placeholder: '请输入',
      label: '请款时间',
      width: 240,
      attrs: {
        valueFormat: 'YYYY-MM-DD HH:mm:ss',
        timePickerProps: { defaultValue: ['00:00:00', '23:59:59'] },
      },
    },
  ])
  const urgentStatusMap = {
    0: '正常',
    1: '加急',
    2: '紧急',
  }

  const tabs = [
    { key: 10, title: '待审核' },
    { key: 20, title: '待付款' },
    { key: 30, title: '已驳回' },
    { key: 40, title: '已完成' },
    { key: 0, title: '已作废' },
  ]
  const paymentStatusMap = {
    10: '待审核',
    20: '待付款',
    30: '已驳回',
    40: '已完成',
    0: '已作废',
  }

  let searchVal = ref<any>({
    pageSize: 20,
    pageNum: 1,
    paymentStatus: '',
  })
  const sortable = reactive({
    sortDirections: ['descend', 'ascend'],
    sorter: true,
  }) as any
  const total = ref(0)
  const tableLoading = ref(false)
  const tableList = ref<Array<any>>([])

  const selectIds = ref([])
  const tableRef = ref()
  const countMap = ref<any>({})
  const submitLoading = ref(false)
  const showUpdateBill = ref(false)
  const showAuditDialog = ref(false)
  const showBillDetail = ref(false)

  const showEditRemarkDialog = ref(false)
  const showEndDialog = ref(false)
  const editRemarkVal = ref()
  const currentData = ref<any>({})

  let filterData = {}
  let tableListMap = {}
  let currentIds: Array<any> = []

  //供应商列表
  async function getSupplierList() {
    const res: any = await findSupperList()
    filterItem.value[0].optionItems = res?.data?.map((el: any) => {
      return {
        label: el.supplierName,
        value: el.id,
      }
    })
  }

  // 切换状态
  function changeStatus(status: number | string) {
    searchVal.value.paymentStatus = status
    searchVal.value.pageNum = 1
    getTableList()
  }

  // 分页
  function changePage(val: number) {
    searchVal.value.pageNum = val
    getTableList()
  }
  function sizeChange(val: number) {
    searchVal.value.pageSize = val
    getTableList()
  }
  // 剩余时间
  function getSurplusTime(time: string) {
    if (!time) return '--'
    let _time = dayjs(time).format('YYYY-MM-DD 23:59:59')
    let hours = dayjs(_time).diff(dayjs(), 'hour')
    if (hours > 0) {
      return `<span style="color: rgb(var(--warning-5))">剩余${parseInt(hours / 24)}天${hours % 24}小时</span>`
    } else {
      let _hours = hours * -1
      return `<span class="warningColor">超时${parseInt(_hours / 24)}天${_hours % 24}小时</span>`
    }
  }
  // 排序
  function sorterChange(dataIndex: string, direction: string) {
    if (!direction) {
      searchVal.value.sortField = null
      searchVal.value.sortType = null
    } else {
      searchVal.value.sortField = dataIndex
      searchVal.value.sortType = direction == 'ascend' ? 1 : -1
    }
    getTableList()
  }
  function selectColumn(val: any) {
    selectIds.value = val
  }
  // 通过条件查询用户列表
  function searchByVal(info: any) {
    searchVal.value.pageNum = 1
    filterData = JSON.parse(JSON.stringify(info)) || {}
    getTableList()
  }
  // 查询合计
  async function getCountList(params: any) {
    const res: any = await findPaymentOrderSum(params)
    countMap.value = res?.data || {}
  }
  // 获取列表
  async function getTableList() {
    let params = {
      ...searchVal.value,
      ...filterData,
    }
    tableLoading.value = true
    const res: any = await findPaymentOrderPage(params)
    tableRef.value.selectAll(false)
    tableLoading.value = false
    tableList.value = res?.data?.records || []
    total.value = res?.data?.total || 0
    tableListMap = {}
    tableList.value.forEach((el: any) => {
      tableListMap[el.id] = el
    })
    getCountList(params)
  }
  // 打卡编辑备注
  function openEditRemarkDialog(row: any) {
    currentData.value = row
    showEditRemarkDialog.value = true
  }
  // 编辑备注
  async function submitRemark() {
    const res: any = await updatePaymentOrderRemark({
      ids: [currentData.value.id],
      remark: editRemarkVal.value,
    })
    if (!res) return false
    Message.success('修改备注成功')
    getTableList()
  }
  // 作废请款单
  function openEndDialog(row: any) {
    currentData.value = row
    showEndDialog.value = true
  }
  // 结束货款
  async function submitEnd() {
    const res: any = await cancelPaymentOrder({
      ids: [currentData.value.id],
    })
    if (!res) return false
    Message.success('该单据已作废')
    getTableList()
  }

  // 编辑
  function openEditDialog(row?: any) {
    currentData.value = row
    showUpdateBill.value = true
  }
  // 审核
  function openAuditDialog(ids: any) {
    if (!ids.length) {
      Message.error('请选择请款单')
      return
    }
    currentIds = ids
    showAuditDialog.value = true
  }
  // 开始审核
  async function audit(auditRes: any) {
    const res: any = await auditPaymentOrder({
      ids: currentIds,
      pass: auditRes.state,
      remark: auditRes.result,
    })
    if (res) {
      Message.success(auditRes.state ? '审核通过' : '已驳回')
      getTableList()
    }
  }
  // 提交审核
  function submitAudit(ids: Array<string>) {
    if (!ids.length) {
      Message.error('请选择请款单')
      return
    }
    Modal.confirm({
      title: '提交审核',
      content: `请再次确认是否需要提交审核`,
      cancelText: '取消',
      okText: '确认',
      titleAlign: 'start',
      onOk: async () => {
        const res: any = await submitPaymentOrder({ ids: ids })
        if (res) {
          Message.success('提交审核成功')
          getTableList()
        }
      },
    })
  }
  // 打开详情
  function openBillDetail(row: any, type: string) {
    currentData.value = row
    currentData.value.detailType = type
    showBillDetail.value = true
  }
</script>
<style lang="less" scoped>
  :deep(.arco-tabs-nav-tab) {
    background-color: #fff;
  }
</style>
